package com.shinemo.mpush.alloc.handler;

import java.io.IOException;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.mpush.api.chat.ChatSession;
import com.mpush.api.chat.ChatSessionNotification;
import com.mpush.api.protocol.PushType;
import com.mpush.api.push.MsgType;
import com.mpush.api.push.PushContent;
import com.mpush.api.push.PushContext;
import com.mpush.api.push.PushMsg;
import com.mpush.api.push.PushSender;
import com.mpush.netty.http.HttpClient;
import com.mpush.tools.Jsons;
import com.shinemo.mpush.alloc.common.ResultCode;
import com.shinemo.mpush.alloc.http.HttpRequest;
import com.shinemo.mpush.alloc.http.HttpResponse;
import com.shinemo.mpush.alloc.service.MesIdService;
import com.shinemo.mpush.alloc.vo.ChatSessionResponse;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;

public class SessionHandler implements HttpHandler {

	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	private PushSender pushSender = null;
	private MesIdService mesIdService = null;

	public SessionHandler(PushSender pushSender, MesIdService mesIdService) {
		this.pushSender = pushSender;
		this.mesIdService = mesIdService;
	}

	@Override
	public void handle(HttpExchange httpExchange) throws IOException {
		
		ChatSessionResponse response=new ChatSessionResponse();
		try {
			String body = HttpRequest.getBody(httpExchange);
			logger.info("接收到的消息:{}", body);
			Map<String, Object> params=HttpRequest.toMap(body);

			response = this.sendPush(params);
		}
		catch(Exception e) {
			logger.error("",e);
			response.setCode(ResultCode.INTERNAL_SERVER_ERROR.getCode());
			response.setMes("内部错误");
		}
		HttpResponse.writeJson(httpExchange, Jsons.toJson(response));
	}

	private ChatSessionResponse sendPush(Map<String, Object> params) {

		ChatSession chatSession = Jsons.fromJson(Jsons.toJson(params), ChatSession.class);
		ChatSessionNotification chatSessionNotification = Jsons.fromJson(Jsons.toJson(params),
				ChatSessionNotification.class);

		PushContent pushContent = new PushContent(PushType.CREATE_SESSION, Jsons.toJson(chatSession));

		PushMsg pushMsg = PushMsg.build(MsgType.NOTIFICATION_AND_MESSAGE, Jsons.toJson(pushContent));
		pushMsg.setMsgId(mesIdService.createMesId());

		pushSender.send(PushContext.build(pushMsg).setUserId(chatSessionNotification.getUserId()));

		ChatSessionResponse response = new ChatSessionResponse();
		response.setCode(ResultCode.SUCCESS.getCode());
		response.setMes("成功");
		return response;
	}

}
